package tests.create;

import static org.junit.Assert.*;

import java.net.UnknownHostException;

import model.Budget;
import model.BudgetFactory;
import model.Line;
import model.Transaction;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.LineInterface;
import cc.test.bridge.SublineInterface;
import cc.test.bridge.TransactionInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class TransactionCreateTest00
{
	Budget budget;
	BudgetFactory factory;
	LineInterface line;
	SublineInterface subline;
	TransactionInterface trans;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Before
	public void setUp() throws Exception
	{
		factory = new BudgetFactory();
		budget = (Budget) factory.create();
        budget.setName("Test budget");
        budget.setDescription("This is a test budget.");
        line = (Line) budget.createLine();
        budget.add(line);
        subline = (Line) line.createSubline();
		line.add((SublineInterface) subline);
	}

	@After
	public void tearDown() throws Exception
	{
		Mongo mongo = null;
  		try
  		{
  			mongo = new Mongo();
  		} catch (UnknownHostException e)
  		{
  			e.printStackTrace();
  		} catch (MongoException e)
  		{
  			e.printStackTrace();
  		}
  		
          DB db = mongo.getDB("cc");
          DBCollection collection = db.getCollection(budget.getRepositoryName());
          collection.remove(new BasicDBObject("entry.id", budget.getId()));
          
          collection = db.getCollection(line.getRepositoryName());
          collection.remove(new BasicDBObject("entry.id", line.getId()));
          
          collection = db.getCollection(subline.getRepositoryName());
          collection.remove(new BasicDBObject("entry.id", subline.getId()));
          
          collection = db.getCollection(trans.getRepositoryName());
          collection.remove(new BasicDBObject("entry.id", trans.getId()));
//		Helper.delete(trans, WorkletContext.getInstance());
//		Helper.delete(subline, WorkletContext.getInstance());
//		Helper.delete(line, WorkletContext.getInstance());
//		Helper.delete(budget, WorkletContext.getInstance());
	}

	@Test
	public void test()
	{
		try
        {
			 trans = subline.createTransaction();
			 subline.add(trans);
			 
			 Boolean successful = budget.commit();
			 if(!successful){
				fail("Could not create/add subline");
			 }
        }
		 catch(Exception e) {
			 e.printStackTrace();
			 fail("Subline create failed with exception " + e);
		 }
	}

}
